package com.ian.offer;

/**
 * @author zhangyaowen
 * @date 2021/3/9 10:23 下午
 */
public class ReverseWords {

    public String reverseWords(String s) {
        s =s.trim();
       int  i =  s.length()-1;
       int j = i;
       StringBuilder builder = new StringBuilder();
       while(i>=0){
           while(i>=0 && s.charAt(i)!=' ')i--;
           builder.append(s.substring(i+1,j+1) + " ");
           while(i>=0 && s.charAt(i)==' ')i--;
           j= i;
       }

        return  builder.toString().trim();

    }

    public String re(String s){
        s = s.trim(); // 删除首尾空格
        int j = s.length() - 1, i = j;
        StringBuilder res = new StringBuilder();
        while(i >= 0) {
            while(i >= 0 && s.charAt(i) != ' ') i--; // 搜索首个空格
            res.append(s.substring(i + 1, j + 1) + " "); // 添加单词
            while(i >= 0 && s.charAt(i) == ' ') i--; // 跳过单词间空格
            j = i; // j 指向下个单词的尾字符
        }
        return res.toString().trim(); // 转化为字符串并返回

    }

    public static void main(String[] args) {
        ReverseWords reverseWords = new ReverseWords();

        System.out.println(reverseWords.reverseWords("a good   example"));
    }
}
